﻿using Polly;
using Polly.CircuitBreaker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class CircuitBreaker : DemoBase
    {
        public override string DemoName => "Polly-Basic CircuitBreaker Demo";

        public override void RunDemo()
        {
            base.Init();

            int runTimes = 8;
            int exceptionTimes = runTimes - 3;
            int durationOfBreak = 5;

            var policy = Policy
                .Handle<Exception>()
                .CircuitBreaker(exceptionTimes, TimeSpan.FromSeconds(durationOfBreak));

            for (int i = 1; i <= runTimes; i++)
            {
                try
                {
                    PrintInfo($"第{i}次执行");
                    policy.Execute(RequestFromWeb);
                }
                catch (BrokenCircuitException e)
                {
                    PrintError($"熔断触发{nameof(BrokenCircuitException)}异常：{e.Message}");
                }
                catch (Exception e)
                {
                    PrintError($"异常：{e.GetType().Name},{e.Message}");
                }
            }
        }

        private void RequestFromWeb()
        {
            throw new Exception("调用方法抛出异常");
        }

    }
}
